package cn.rongdao.jrkabao.ui.city;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRFileUtils;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.sidebar.SideBar;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.mifengkong.greendao.bean.CityInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.FRBaseNeedLocationActivity;
import cn.rongdao.jrkabao.bean.city.CityListBean;
import cn.rongdao.jrkabao.bean.city.SortBean;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.dao.CityDao;
import cn.rongdao.jrkabao.model.city.CityModel;
import cn.rongdao.jrkabao.ui.city.adapter.GradViewHotCityAdapter;
import cn.rongdao.jrkabao.ui.city.adapter.SortAdapter;
import cn.rongdao.jrkabao.ui.city.event.UpdateCityNameEvent;
import cn.rongdao.jrkabao.ui.city.util.CharacterParser;
import cn.rongdao.jrkabao.ui.city.util.PinyinComparator;
import cn.rongdao.jrkabao.ui.city.widget.GridViewForScrollview;
import cn.rongdao.jrkabao.util.gson.GsonTools;

/**
 * Created by jack on 17/5/11
 */

public class CityActivity extends FRBaseNeedLocationActivity implements View.OnClickListener {

    @BindView(R.id.ac_retry_textview)
    TextView mAcRetryTextview;

    public static void start(Context context) {
        FRStartActivity.start(context, CityActivity.class);
    }

    @BindView(R.id.ac_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.sortlist)
    ListView sortListView;
    @BindView(R.id.sidebar)
    SideBar sideBar;

    private TextView mCurrentCity;
    private View mHeadView;
    private GridViewForScrollview gridViewForScrollview;

    private SortAdapter adapter;
    private List<CityListBean.DataBean> mDataEntityList = new ArrayList<>();
    private List<CityListBean.DataBean> mHotCityList = new ArrayList<>();

    private CharacterParser characterParser;

    @Override
    protected boolean diffStatusBar() {
        return true;
    }

    @Override
    protected void initView() {
        initTitleBar();
        mHeadView = View.inflate(this, R.layout.layout_city_head, null);
        gridViewForScrollview = (GridViewForScrollview) mHeadView.findViewById(R.id.activity_city_head_gridview);
        mCurrentCity = (TextView) mHeadView.findViewById(R.id.activity_city_head_loaction);
        mCurrentCity.setOnClickListener(this);
        initData();
    }

    private void initData() {
        if (sortListView.getHeaderViewsCount() == 0) {
            sortListView.addHeaderView(mHeadView);
        }
        if (!FRString.isEmpty(CityDao.getInstance().getCityName())) {
            mCurrentCity.setText(CityDao.getInstance().getCityName());
        }
        getData();

    }

    private void getData() {
        if (FRFileUtils.exists(this, SPConstant.CITYNAME)) {
            parseData(FRFileUtils.read(SPConstant.CITYNAME));
        } else {
            getDataFromNet();
        }
    }

    private void getDataFromNet() {
        CityModel.getInstance().execute(new FRBaseObserver<String>(this, "正在加载...") {
            @Override
            protected void onBaseNext(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int status = jsonObject.getInt("status");
                    if (status == 1) {
                        FRFileUtils.deleteFile(CityActivity.this, SPConstant.CITYNAME);
                        FRFileUtils.saveWithRepalce(SPConstant.CITYNAME, data);
                        parseData(data);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            protected void onBaseError(Throwable t) {
                showErrorView();
            }
        });
    }

    private void showErrorView() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAcRetryTextview.setVisibility(View.VISIBLE);
            }
        });
    }

    private void parseData(String data) {
        CityListBean cityListBean = GsonTools.changeGsonToBean(data, CityListBean.class);
        if (cityListBean != null && cityListBean.getData() != null) {
            mDataEntityList = cityListBean.getData();
            sortList();
        } else {
            showErrorView();
        }
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitle("选择城市");
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 给获取到的城市地址集进行排序
     */
    private void sortList() {
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        PinyinComparator pinyinComparator = new PinyinComparator();


        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @SuppressLint("NewApi")
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });

        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    return;
                }
                SortBean sortBean = ((SortBean) adapter.getItem(position - 1));
                String name = sortBean.getName();
                int city_id = sortBean.getCity_id();
                if (CityDao.getInstance().isHaveCityInfo()) {
                    CityDao.getInstance().updateCityIdAndName(FRString.valueOf(city_id), FRCollection.appendAsString(name, "市", ""));
                } else {
                    CityDao.getInstance().insertObject(new CityInfo(FRString.valueOf(city_id), FRCollection.appendAsString(name, "市", "")));
                }
                EventBus.getDefault().post(new UpdateCityNameEvent());
                finish();
            }
        });

        List<String> cityNames = new ArrayList<>();
        List<String> cityIds = new ArrayList<>();
        for (int i = 0; i < mDataEntityList.size(); i++) {
            String cityName = mDataEntityList.get(i).getName();
            String mCityId = mDataEntityList.get(i).getCity_id();
            cityNames.add(cityName);
            cityIds.add(mCityId);
            if (mDataEntityList.get(i).getPhoneticize().contains("#")) {
                CityListBean.DataBean hotcity = new CityListBean.DataBean();
                hotcity.setName(mDataEntityList.get(i).getName());
                hotcity.setCity_id(mDataEntityList.get(i).getCity_id());
                mHotCityList.add(hotcity);

            }

        }
        GradViewHotCityAdapter mGradViewHotCityAdapter = new GradViewHotCityAdapter(this, mHotCityList.subList(0, mHotCityList.size() > 9 ? 9 : mHotCityList.size()));
        gridViewForScrollview.setAdapter(mGradViewHotCityAdapter);
        gridViewForScrollview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CityListBean.DataBean mCityBean = ((CityListBean.DataBean) parent.getItemAtPosition(position));
                String name = mCityBean.getName();
                String city_id = mCityBean.getCity_id();
                if (CityDao.getInstance().isHaveCityInfo()) {
                    CityDao.getInstance().updateCityIdAndName(FRString.valueOf(city_id), FRCollection.appendAsString(name, "市", ""));
                } else {
                    CityDao.getInstance().insertObject(new CityInfo(FRString.valueOf(city_id), FRCollection.appendAsString(name, "市", "")));
                }
                EventBus.getDefault().post(new UpdateCityNameEvent());
                finish();
            }
        });

        String[] citysName = new String[]{};
        String[] citysId = new String[]{};
        citysName = cityNames.toArray(citysName);
        citysId = cityIds.toArray(citysId);
        List<SortBean> sourceDateList = filledData(citysName, citysId);

        // 根据a-z进行排序源数据
        Collections.sort(sourceDateList, pinyinComparator);
        adapter = new SortAdapter(this, sourceDateList);
        sortListView.setAdapter(adapter);
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<SortBean> filledData(String[] date, String[] id) {
        List<SortBean> mSortList = new ArrayList<>();

        for (int i = 0; i < date.length; i++) {
            SortBean sortBean = new SortBean();
            sortBean.setName(date[i]);
            sortBean.setCity_id(Integer.parseInt(id[i]));
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortBean.setSortLetters(sortString.toUpperCase());
            } else {
                sortBean.setSortLetters("#");
            }

            mSortList.add(sortBean);
        }
        return mSortList;

    }


    @Override
    public void onReceiveLocation(final BDLocation location) {
        if (null != location && location.getLocType() != BDLocation.TypeServerError) {
            StringBuilder sb = new StringBuilder(256);
            sb.append("time : ");
            /**
             * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
             * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
             */
            sb.append(location.getTime());
            sb.append("\nlocType : ");// 定位类型
            sb.append(location.getLocType());
            sb.append("\nlocType description : ");// *****对应的定位类型说明*****
            sb.append(location.getLocTypeDescription());
            sb.append("\nlatitude : ");// 纬度
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");// 经度
            sb.append(location.getLongitude());
            sb.append("\nradius : ");// 半径
            sb.append(location.getRadius());
            sb.append("\nCountryCode : ");// 国家码
            sb.append(location.getCountryCode());
            sb.append("\nCountry : ");// 国家名称
            sb.append(location.getCountry());
            sb.append("\ncitycode : ");// 城市编码
            sb.append(location.getCityCode());
            sb.append("\ncity : ");// 城市
            sb.append(location.getCity());
            sb.append("\nDistrict : ");// 区
            sb.append(location.getDistrict());
            sb.append("\nStreet : ");// 街道
            sb.append(location.getStreet());
            sb.append("\naddr : ");// 地址信息
            sb.append(location.getAddrStr());
            sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
            sb.append(location.getUserIndoorState());
            sb.append("\nDirection(not all devices have value): ");
            sb.append(location.getDirection());// 方向
            sb.append("\nlocationdescribe: ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            sb.append("\nPoi: ");// POI信息
            if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                for (int i = 0; i < location.getPoiList().size(); i++) {
                    Poi poi = location.getPoiList().get(i);
                    sb.append(poi.getName()).append(";");
                }
            }
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 速度 单位：km/h
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());// 卫星数目
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 海拔高度 单位：米
                sb.append("\ngps status : ");
                sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                // 运营商信息
                if (location.hasAltitude()) {// *****如果有海拔高度*****
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 单位：米
                }
                sb.append("\noperationers : ");// 运营商信息
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            if (mDataEntityList == null || mDataEntityList.size() <= 0) {
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        locateSuccess(location);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_city;
    }

    /**
     * 定位成功后做的操作
     *
     * @param location
     */
    private void locateSuccess(BDLocation location) {
        if (TextUtils.isEmpty(location.getCity())) {
            mCurrentCity.setText("定位失败，请手动选择城市");
            return;
        }
        String locationCity = location.getCity();
        mCurrentCity.setText("定位成功 当前定位城市：" + locationCity);
        mCurrentCity.setEnabled(true);
        for (CityListBean.DataBean dataEntity : mDataEntityList) {
            boolean isContains = locationCity.contains(dataEntity.getName());
            if (isContains) {
                if (CityDao.getInstance().isHaveCityInfo()) {
                    CityDao.getInstance().updateCityIdAndName(dataEntity.getCity_id(), locationCity);
                } else {
                    CityDao.getInstance().insertObject(new CityInfo(dataEntity.getCity_id(), locationCity));
                }
                break;
            }
        }
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_city_head_loaction:
                if (mLocationService != null) {
                    startLocate();
                    mCurrentCity.setText("正在定位...请稍候");
                    mCurrentCity.setEnabled(false);
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (FRString.isEmpty(CityDao.getInstance().getCityId())) {
            FRToast.showToastSafe("请先选择所在城市，以便我们为您提供更好的服务");
        }
        return super.onKeyDown(keyCode, event);
    }


    @OnClick(R.id.ac_retry_textview)
    public void onViewClicked() {
        getData();
        mAcRetryTextview.setVisibility(View.GONE);
    }
}